package com.beijiteshop.libcommon.utils

import android.content.Context
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.beijiteshop.libcommon.R
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/3 13:53
 * @Description 图片加载工具类
 */
object ImageLoadUtil {

    private val TAG = this::class.java.simpleName

    /**
     * 加载网络图片
     */
    fun loadImage(url: String, imageView: ImageView){
        Glide.with(imageView.context)
            .load(url)
            .placeholder(R.drawable.image_placeholder)
            .error(R.drawable.image_placeholder)
            .thumbnail(.1f)
            .centerCrop()
            .into(imageView)
    }

    /**
     * 加载本地图片资源
     */
    fun loadDrawableRes(imageView: ImageView, drawable: Int){
        Glide.with(imageView.context).load(ContextCompat.getDrawable(imageView.context,drawable)).into(imageView)
    }

    /**
     * 加载自适应高度图片(长图)
     */
    fun loadImageByWrap(url: String,imageView: ImageView){
        val width = ScreenUtils.getScreenWidth().toFloat()
        Glide.with(imageView.context).load(url).apply(
            RequestOptions().centerCrop()
        ).into(object : CustomTarget<Drawable>(){
            override fun onLoadCleared(placeholder: Drawable?) {

            }

            override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                val resize = resource.intrinsicWidth.toFloat() / width
                imageView.background = resource
                val params = imageView.layoutParams
                params.width = width.toInt()
                params.height = (resource.intrinsicHeight/resize).toInt()
                imageView.layoutParams = params
            }
        })
    }

    /**
     * 加载圆形图片
     */
    fun loadCircle(url: String,imageView: ImageView){
        if (url.isEmpty()){
            return
        }
        Glide.with(imageView.context).load(url).apply(
            RequestOptions.bitmapTransform(CircleCrop())
        ).into(imageView)
    }

}